<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="./css/login_singup.css">
    <script src="js/jquery.min.js"></script>
</head>

<body>
<div class="container">
    <div class="login-wrapper">
        <div class="header">Login</div>
        <div class="form-wrapper">
            <input id="username" type="text" name="username" placeholder="手机号" class="input-item">
            <input id="password" type="password" name="password" placeholder="密码" class="input-item">
            <button class="btn" onclick="submit()">Login</button>
        </div>
        <div class="msg">
            Don't have account?
            <a href="singup.html">Sign up</a>
        </div>
    </div>
</div>

<script>
    function submit() {
        // 1. 进行非空校验
        let username = jQuery("#username");
        let password = jQuery("#password");

        if (username.val().trim() === "") {
            alert("请输入手机号");
            username.focus();
            return false;
        }
        if (password.val().trim() === "") {
            alert("请输入密码");
            username.focus();
            return false;
        }
        for (let i = 0; i < username.val().trim().length; i++) {
            if (isNaN(Number(username.val().trim()[i])) || username.val().trim()[i] === ' ') {
                alert("手机号中出现非法字符!");
                username.focus();
                return false;
            }
        }
        if (username.val().trim().length !== 11) {
            alert("请输入 11 位有效的手机号");
            username.focus();
            return false;
        }

        // 2. 发送登录请求给后端
        jQuery.ajax({
            url: "user/login",
            type: 'post',
            data: {
                username: username.val(),
                password: password.val()
            },
            success: function (body) {
                if (body.userid <= 0) {
                    alert("用户名或密码错误!");
                } else {
                    alert("登录成功! 跳转到主页");
                    location.href = "index.html";
                }
            }
        });
    }
</script>
</body>

</html>